/**
 * @(#)Test.java 2014年12月17日
 * <p>
 * Copyright (c) 2010 35.com, Inc. All rights reserved.
 */
package com.example.demo;


import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class AsymmetricEncryptionExample {

    public static void main(String[] args) throws Exception {
        // 生成密钥对
        KeyPair keyPair = generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 要加密的原始数据
        String plaintext = "这是一段要加密的文本";

        // 使用公钥进行加密
        byte[] encryptedData = encrypt(plaintext.getBytes(), publicKey);
        System.out.println("加密后的数据: " + Base64.getEncoder().encodeToString(encryptedData));

        // 使用私钥进行解密
        byte[] decryptedData = decrypt(encryptedData, privateKey);
        System.out.println("解密后的数据: " + new String(decryptedData));
    }

    // 生成RSA密钥对
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    // 使用公钥加密数据
    public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    // 使用私钥解密数据
    public static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encryptedData);
    }
}